package com.group2.comprehensive_treatment.actualpopulation.resident.handler;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.group2.comprehensive_treatment.actualpopulation.resident.entity.User;
import com.group2.comprehensive_treatment.actualpopulation.resident.service.UserService;
import com.group2.comprehensive_treatment.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * ComprehensiveTreatment
 * com.group2.comprehensive_treatment.actualpopulation.resident.handler
 * 类功能描述
 *
 * @author: August
 * @date: 2025/3/12 20:23
 */

@RestController
@RequestMapping("/user")
@Slf4j
public class UserHandler {

    @Resource
    UserService userService;
    @GetMapping("/login")
    public Map<String,Object> login(User user) {
        log.info("⽤⼾名: [{}]",user.getUsername());
        log.info(" 密码: [{}]",user.getPassword());
        Map<String, Object> map = new HashMap<>();
        try{
            Map<String,String> payload =  new HashMap<>();
            User login = userService.login(user); //开始登录
            System.out.println("handler:" + login);
            if (null != login) {
                payload.put("id",user.getId()+"");
                payload.put("name",user.getUsername());
                payload.put("password",user.getPassword());
                // ⽣成JWT的令牌

                String token = JwtUtils.createToken(payload);
                map.put("state",true);
                map.put("msg"," 认证成功 ");
                        //响应token
                        map.put("token",token);
            }
        }catch (Exception e){
            map.put("state",false);
            map.put("msg",e.getMessage());
        }
        return map;
    }
    @PostMapping("/other")
    public Map<String,Object> test(HttpServletRequest request){
        Map<String, Object> map = new HashMap<>();
        //处理⾃⼰业务逻辑

        String token = request.getHeader("token");
        DecodedJWT verify = JwtUtils.verifyToken(token);
        log.info("⽤⼾ id: [{}]",verify.getClaim("id").asString());
        log.info("⽤⼾ name: [{}]",verify.getClaim("name").asString());
        map.put("state",true);
        map.put("msg"," 请求成功 !");
        return map;
    }


}
